package com.smart.tool.pipeline;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author gao.gwq
 * @Version Pipeline.java, v 0.1 2024年05月27日 11:34 gao.gwq
 * @Description:  管道式调用组件，可以按步骤对数据进行处理
 *
 *   Long resultLong =  Pipeline.of(param->{
 *        System.out.println("param:"+param);
 *        return 900L;
 *    }).addHandler(id->{
 *        System.out.println("id:"+id);
 *        return id+100L;
 *    }).execute("abc");
 *
 */
public class Pipeline<I, O> {

    private  Handler<I, O> currentHandler;

    private Pipeline() {
    }



    public static <I, O> Pipeline<I, O> of(Handler<I, O> currentHandler) {
        return new Pipeline<>(currentHandler);
    }

    private Pipeline(Handler<I, O> currentHandler) {
        this.currentHandler = currentHandler;
    }

    public <K> Pipeline<I, K> addHandler(Handler<O, K> newHandler) {
        if (newHandler == null) {
            throw  new IllegalArgumentException("newHandler is null");
        }

        return new Pipeline<>(input -> newHandler.doProcess(currentHandler.doProcess(input)));
    }

    public O execute(I input) {
        try {
            Map<String,Object> context = new HashMap<>();
            PipelineContext.setContext(context);
            return currentHandler.doProcess(input);
        }finally {
            PipelineContext.removeContext();
        }


    }
}